// 添加ElementPlus相关导入
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import { createApp } from 'vue'
import { createPinia } from 'pinia' // 先导入Pinia
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(createPinia()) // 先安装Pinia
app.use(router) // 再安装路由
app.use(ElementPlus) // 只保留一次ElementPlus注册

// 注册所有Element Plus图标（只保留一次）
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.mount('#app') // 只保留一次挂载调用

// 检查 token 有效期
function parseJwt(token) { 
    var base64Url = token.split('.')[1]; 
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); 
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) { 
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); 
    }).join('')); 
    return JSON.parse(jsonPayload); 
}

function checkTokenExpiration() { 
    const token = localStorage.getItem('token'); 
    if (token) { 
        // 解析 token 获取过期时间 
        const decoded = parseJwt(token); 
        const expirationTime = decoded.exp * 1000; 
        const currentTime = Date.now(); 
        // 如果 token 即将过期（例如剩余 5 分钟），自动刷新 token 或者提示用户重新登录 
        if (expirationTime - currentTime < 5 * 60 * 1000) { 
            // 刷新 token 的逻辑 
      refreshToken();
    }
  }
}

// 定时检查 token 有效期
setInterval(checkTokenExpiration, 60 * 1000); // 每分钟检查一次

function refreshToken() {
  // Get the refresh token from localStorage
  const refreshToken = localStorage.getItem('refreshToken');
  
  if (!refreshToken) {
    // Handle case where there's no refresh token
    console.log('No refresh token available');
    return;
  }
  
  // Make API call to refresh the token
  // Replace with your actual API endpoint
  fetch('/api/auth/refresh', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${refreshToken}`
    }
  })
  .then(response => response.json())
  .then(data => {
    if (data.token) {
      // Store the new token
      localStorage.setItem('token', data.token);
      
      // Optionally store new refresh token if provided
      if (data.refreshToken) {
        localStorage.setItem('refreshToken', data.refreshToken);
      }
    }
  })
  .catch(error => {
    console.error('Error refreshing token:', error);
    // Handle error (e.g., redirect to login)
  });
}
